package com.rsy.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.rsy.auth.config.AuthConfig;
import com.rsy.auth.feign.MemberFeignService;
import com.rsy.common.vo.MemberResponseVo;
import com.rsy.auth.vo.SocialUser;
import com.rsy.common.utils.HttpUtils;
import com.rsy.common.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OauthController {

    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private AuthConfig authConfig;

    /**
     * 第三方登录
     * @param code
     * @param attributes
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/oauth2.0/success")
    public String authorize(String code, RedirectAttributes attributes, HttpSession session) throws Exception {
        //1. 使用code换取token，换取成功则继续2，否则重定向至登录页
        Map<String, String> query = new HashMap<>();
        query.put("client_id", authConfig.getClientId());
        query.put("client_secret", authConfig.getClientSecret());
        query.put("grant_type", authConfig.getGrantType());
        query.put("redirect_uri", authConfig.getRedirectUri());
        query.put("code", code);
        //发送post请求换取token
        HttpResponse response = HttpUtils.doPost(authConfig.getHost(), authConfig.getPath(), "post", new HashMap<String, String>(), query, new HashMap<String, String>());
        Map<String, String> errors = new HashMap<>();
        if (response.getStatusLine().getStatusCode() == 200) {
            //2. 调用member远程接口进行oauth登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {
            });
            R login = memberFeignService.oauth2Login(socialUser);
            //2.1 远程调用成功，返回首页并携带用户信息
            if (login.getCode() == 0) {
                String jsonString = JSON.toJSONString(login.get("data"));
                MemberResponseVo memberResponseVo = JSON.parseObject(jsonString, new TypeReference<MemberResponseVo>() {
                });
//                attributes.addFlashAttribute("loginUser", memberResponseVo);
                //TODO 2、使用json的序列化方式来序列化对象数据到redis中
                session.setAttribute("loginUser",memberResponseVo);
                return "redirect:http://rsy.gulimall.com";
            } else {
                //2.2 否则返回登录页
                errors.put("msg", "登录失败，请重试");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            errors.put("msg", "获得第三方授权失败，请重试");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
